package Arcsight::CaseParser;

use strict;
use XML::Simple;
use Arcsight::Event;
use Arcsight::Case;
use Data::Dumper;

sub parse {
	my $xml = shift;
	my $ref;
	$ref = XMLin($xml, KeyAttr => {Case => 'id', SecurityEvent => 'id'});

	my ($cases,$events);

	# parse out the cases

	if(exists($ref->{'Case'}->{'id'})){
		# we've only got 1 case
		$cases->{$ref->{'Case'}->{'id'}} = Arcsight::Case->new(-id => $ref->{'Case'}->{'id'}, -details => $ref->{'Case'});
	}
	else {
		# we've got n+1 cases
		foreach my $x (keys %{$ref->{'Case'}}){
			$cases->{$x} = Arcsight::Case->new(-id => $x, -details => $ref->{'Case'}->{$x});
		}
	}

	# parse out the events
	if(exists($ref->{'SecurityEvent'}->{'id'})){
		# we only have 1 event
		my $eid = $ref->{'SecurityEvent'}->{'id'};
		$events->{$eid} = Arcsight::Event->new(-id => $eid, -details => $ref->{'SecurityEvent'});
	}
	else {
		# we have n+1 events
		foreach my $eid (keys %{$ref->{'SecurityEvent'}}){
			$events->{$eid} = Arcsight::Event->new(-id => $eid, -details => $ref->{'SecurityEvent'}->{$eid});
		}
	}

	# hook the events under the correct cases

	foreach my $case (keys %$cases){
		my $list = $cases->{$case}->details()->{'caseEvents'}->{'list'}->{'ref'};
		if(uc(ref($list)) eq 'HASH'){
			my $id = $list->{'id'};
			# only 1 event
			$cases->{$case}->events($events->{$list->{'id'}});

			# check for base events
			my $baseEventList = eval { $events->{$list->{'id'}}->details->{'baseEventIds'}->{'list'}->{'ref'} };
			if(uc(ref($baseEventList)) eq 'HASH'){
				my $bid = $baseEventList->{'id'};
				$cases->{$case}->events->{$id}->baseEvents($events->{$bid});
			} else {
				# we have multiple base events
				foreach my $x (@{$baseEventList}){
					my $bid = $x->{'id'};
					$cases->{$case}->events->{$id}->baseEvents($events->{$bid});
				}
			}
		}
		else {
			# n+1 events
			foreach my $x (@{$list}){
				my $id = $x->{'id'};
				$cases->{$case}->events($events->{$events->{$x->{'id'}}});

				# check for base events
				my $baseEventList = $events->{$list->{'id'}}->{'baseEventIds'}->{'ref'};
				if(uc(ref($baseEventList)) eq 'HASH'){
					my $bid = $baseEventList->{'id'};
					$cases->{$case}->events->{$id}->baseEvents($events->{$bid});
				} else {
					# we have multiple base events
					foreach my $x (@{$baseEventList}){
						my $bid = $x->{'id'};
						$cases->{$case}->events->{$id}->baseEvents($events->{$bid});
					}
				}
			}
		}
	}
	return($cases);
}

1;
